#include "borrow.h"
#include "ui_borrow.h"

borrow::borrow(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::borrow)
{
    ui->setupUi(this);

    appDir = QCoreApplication::applicationDirPath();
}

void borrow::on_sureBtn_clicked()
{
    handleBookInfo();

    emit updataView();
}

void borrow::on_cancelBtn_clicked()
{

}

/* 处理图书信息 */
void borrow::handleBookInfo()
{
    QFile bookfile(appDir + "/bookInfo.txt");
    if (bookfile.exists() == false)
    {
        QMessageBox::warning(this, "bookInfo文件打开", "bookInfo文件不存在");
        return;
    }

    bookfile.open(QIODevice::ReadOnly);

    QStringList lines;  //字符串链表

    while (bookfile.atEnd() == false) //文件没结束
    {
        QString line = bookfile.readLine(); // 读取每一行字符串
        lines.append(line);    //读取每一行字符串到链表中
    }
    bookfile.close();

    // 查找并修改目标行
    bool found = false;
    for (int i = 0; i < lines.size(); ++i)
    {
        QString data = lines[i];
        if ((lines[i].split("+")[0] == ui->le_bookname->text()) && (lines[i].split("+")[1] == ui->le_author->text()))
        {
            QString cnt = lines[i].split("+")[2].split("\n")[0];
            if (cnt.toInt() > 1)    //小于2本时不能借
            {
                cnt = QString::number(cnt.toInt() - 1);

                lines[i] = lines[i].split("+")[0] + "+" + lines[i].split("+")[1] + "+" + cnt + "\n"; // 修改该行
                found = true;
                break; // 只需要修改第一个匹配项
            }
            else
            {
                QMessageBox::warning(this, "借阅失败", "该书目前只有1本");
                return;
            }
        }
    }

    if (!found) //没找到
    {
        QMessageBox::warning(this, "借阅失败", "该书不存在");
        return;
    }
    else
    {
        emit updataStuBorrowInfo(ui->le_bookname->text(), ui->le_author->text());
        emit handleStuInfo();

        this->hide();
        ui->le_bookname->clear();
        ui->le_author->clear();
        QMessageBox::warning(this, "借阅成功", "该书已借阅");
    }

    bookfile.open(QIODevice::WriteOnly);

    QTextStream out(&bookfile);
    // 设置编码为 UTF-8
    out.setCodec("UTF-8");
    for (int idx = 0; idx < lines.size(); idx++)
    {
        out << lines[idx];
    }

    bookfile.close();
}

borrow::~borrow()
{
    delete ui;
}
